package top.songxs.gmall.order.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.songxs.gmall.order.service.OrderInfoService;
import top.songxs.gmall.rabbit.constant.MqConstant;
import top.songxs.gmall.rabbit.service.RabbitMqBizService;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class CloseOrderListener {

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private RabbitMqBizService rabbitMqBizService;

    @RabbitListener(queues = MqConstant.CLOSE_QUEUE_NAME)
    public void closeOrderListener(Message message, Channel channel) {
        byte[] body = message.getBody();
        String msg = new String(body);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        Map<String, Object> hashMap = JSON.parseObject(msg, HashMap.class);
        String orderId = hashMap.get("orderId").toString();
        String userId = hashMap.get("userId").toString();
        try {
            //执行关闭订单方法
            //手动应答，返回我们的ack
            orderInfoService.closeOrder(Long.parseLong(orderId), Long.parseLong(userId));
                channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            e.printStackTrace();
            //重试代码
            rabbitMqBizService.retry(message,channel,3);

            try {
                channel.basicNack(deliveryTag, true, true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }


    }
}
